package com.carrot.api.controller.system;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.carrot.common.core.controller.BaseController;
import com.carrot.common.core.domain.AjaxResult;
import com.carrot.common.core.domain.dto.SysPointUnitMapDto;
import com.carrot.common.core.domain.entity.SysPointUnitMap;
import com.carrot.common.core.domain.vo.SysPointUnitMapVo;
import com.carrot.common.exception.ServiceException;
import com.carrot.common.mybatis.Page;
import com.carrot.common.utils.StringUtils;
import com.carrot.system.service.ISysPointUnitMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 点表字段单位
 *
 * @author liuhongzhen
 */
@RestController
@RequestMapping("/system/point-unit")
public class BasicsUnitController extends BaseController {

    @Autowired
    private ISysPointUnitMapService unitService;

    @PostMapping("/list")
    public AjaxResult list(@Validated @RequestBody SysPointUnitMapDto dto) {

        Page<SysPointUnitMap, SysPointUnitMapVo> page =
                new Page<>(dto.getPageNum(), dto.getPageSize());

        QueryWrapper<SysPointUnitMap> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(dto.getSearchContent())) {
            queryWrapper
                    .like("other_unit", dto.getSearchContent())
                    .or()
                    .like("unit", dto.getSearchContent())
                    .or()
                    .like("factor", dto.getSearchContent());
        }

        queryWrapper.orderByAsc("create_time");
        page.setQueryWrapper(queryWrapper);

        page = unitService.findPage(page);

        return AjaxResult.success(page.getPageData());
    }

    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam("id") Long id) {

        SysPointUnitMap unitMap = unitService.getById(id);
        return AjaxResult.success(unitMap);
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysPointUnitMap pointUnitMap) {

        unitService.add(pointUnitMap);
        return AjaxResult.success();
    }


    @PostMapping("/update")
    public AjaxResult update(@RequestBody SysPointUnitMap pointUnitMap) {

        unitService.update(pointUnitMap);
        return AjaxResult.success();
    }


    @GetMapping("/del")
    public AjaxResult del(@RequestParam("id") Long id) {

        unitService.del(id);
        return AjaxResult.success();
    }


    @PostMapping("/batchDel")
    public AjaxResult batchDel(@RequestBody SysPointUnitMapDto dto) {
        if (CollUtil.isEmpty(dto.getIds())) {
            throw new ServiceException("参数校验失败");
        }
        unitService.batchDel(dto.getIds());
        return AjaxResult.success();
    }
}
